package com.vx.vxbug.services;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailService implements UserDetailsService {

	@Autowired
	private UserService userService;

	public UserDetails loadUserByUsername(String username) {
		com.vx.vxbug.entities.User u = userService.getUserByLogin(username);
		if (u != null) {
			return new User(u.getLogin(), u.getPassword(), Collections.singleton(createAuthority(u)));
		} else {
			throw new UsernameNotFoundException("user not found");
		}
	}

	private GrantedAuthority createAuthority(com.vx.vxbug.entities.User u) {
		return new SimpleGrantedAuthority(u.getRole());
	}

}
